package com.ruoyi.system.utils;

import cn.hutool.core.util.ObjectUtil;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.ruoyi.system.domain.PmsPurchaseOrders;
import com.ruoyi.system.domain.PmsPurchaseRequisitionsDetail;
import com.ruoyi.system.domain.WmsSuppliers;
import com.ruoyi.system.domain.bo.PmsPurchaseOrdersBo;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.List;

public class PurchaseOrderPdfGenerator {

    /**
     * 生成采购订单PDF
     * @param order       采购订单数据
     * @param supplier    供应商数据
     * @param items       商品明细列表
     * @param outputPath  PDF保存路径
     */
    public static void generatePurchaseOrderPdf(
        PmsPurchaseOrders order,
        WmsSuppliers supplier,
        List<PmsPurchaseRequisitionsDetail> items,
        String outputPath
    ) throws IOException {
        // 1. 初始化PDF文档
        PdfWriter writer = new PdfWriter(new File(outputPath));
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);
        document.setMargins(30, 30, 30, 30);

        // 加载内置的中文字体（需 itext-asian 依赖）
        PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
        document.setFont(font);

        // 2. 添加公司Logo（可选）
        try {
            ImageData logoData = ImageDataFactory.create("D:\\ruoyi\\uploadPath\\company_logo.jpg");
            Image logo = new Image(logoData).setWidth(100).setHorizontalAlignment(HorizontalAlignment.CENTER);
            document.add(logo);
        } catch (MalformedURLException e) {
            System.err.println("Logo图片路径无效，跳过LOGO添加");
        }

        // 3. 添加标题
        document.add(new Paragraph("采购订单 (PURCHASE ORDER)")
            .setTextAlignment(TextAlignment.CENTER)
            .setFontSize(16)
            .setBold()
            .setMarginBottom(20));

        // 4. 添加订单基本信息（两列布局）
        float[] columnWidths = {300f, 300f};
        Table infoTable = new Table(columnWidths);
        infoTable.addCell(createCell("订单编号:", order.getPoCode(), true));
        infoTable.addCell(createCell("供应商:", supplier.getSupplierName(), true));// 在生成PDF的代码中：
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        infoTable.addCell(createCell("订单日期:", sdf.format(order.getOrderDate()), true));
        infoTable.addCell(createCell("联系人:", supplier.getContactName(), true));
        infoTable.addCell(createCell("预计交货日期:", sdf.format(order.getExpectedDeliveryDate()), true));
        infoTable.addCell(createCell("电话:", supplier.getContactPhone(), true));
        String paymentTerms = order.getPaymentTerms() != null ? order.getPaymentTerms() : "无";
        infoTable.addCell(createCell("付款条款:", paymentTerms, true));
        infoTable.addCell(createCell("邮箱:", supplier.getEmail(), true));
        document.add(infoTable);

        // 5. 添加商品明细表格
        document.add(new Paragraph("\n商品明细")
            .setBold()
            .setMarginTop(15));

        Table itemTable = new Table(UnitValue.createPercentArray(new float[]{3, 2, 2, 2, 2, 2}));
        itemTable.setWidth(UnitValue.createPercentValue(100));

        // 表头
        itemTable.addHeaderCell(createHeaderCell("商品名称"));
        itemTable.addHeaderCell(createHeaderCell("规格"));
        itemTable.addHeaderCell(createHeaderCell("数量"));
        itemTable.addHeaderCell(createHeaderCell("单价"));
        itemTable.addHeaderCell(createHeaderCell("税率"));
        itemTable.addHeaderCell(createHeaderCell("金额"));

        // 商品行
        for (PmsPurchaseRequisitionsDetail item : items) {
            itemTable.addCell(createCell(item.getProductName()));
            itemTable.addCell(createCell(item.getProductSpec()));
            itemTable.addCell(createCell(item.getTotalQuantity().toString()));
            itemTable.addCell(createCell(item.getPurchasePrice().toString()));
            itemTable.addCell(createCell("13%")); // 假设固定税率13%
            itemTable.addCell(createCell(item.getTotalAmount().toString()));
        }

        document.add(itemTable);

        // 6. 添加合计金额
        document.add(new Paragraph("\n")
            .add(new Text("合计金额（不含税）: ").setBold())
            .add(new Text(order.getTotalAmount().toString()))
            .setTextAlignment(TextAlignment.RIGHT));

        if(ObjectUtil.isNull(order.getTotalTax())){
            order.setTotalTax(new BigDecimal(0));
        }

        document.add(new Paragraph()
            .add(new Text("税额: ").setBold())
            .add(new Text(order.getTotalTax().toString()))
            .setTextAlignment(TextAlignment.RIGHT));

        BigDecimal totalAmountWithTax = order.getTotalAmount().add(order.getTotalTax());

        document.add(new Paragraph()
            .add(new Text("合计金额（含税）: ").setBold())
            .add(new Text(totalAmountWithTax.toString()))
            .setTextAlignment(TextAlignment.RIGHT));

        // 7. 添加备注和签章
        document.add(new Paragraph("\n备注:")
            .setBold()
            .setMarginTop(20));
        document.add(new Paragraph("1. 请按约定日期交货，逾期将按合同条款处理。"));
        document.add(new Paragraph("2. 收货地址："+supplier.getAddress()));

        document.add(new Paragraph("\n\n供应商确认签章：________________________")
            .setMarginTop(30));

        document.close();
        System.out.println("PDF生成成功: " + outputPath);
    }

    // 创建表格单元格（通用）
    private static Cell createCell(String content) {
        return new Cell().add(new Paragraph(content)).setPadding(5);
    }

    // 创建表格单元格（带标签）
    private static Cell createCell(String label, String value, boolean isBoldLabel) {
        Paragraph p = new Paragraph();
        if (isBoldLabel) {
            p.add(new Text(label).setBold());
        } else {
            p.add(label);
        }
        p.add(" " + value);
        return new Cell().add(p).setPadding(5);
    }

    // 创建表头单元格
    private static Cell createHeaderCell(String content) {
        return new Cell()
            .add(new Paragraph(content).setBold())
            .setBackgroundColor(ColorConstants.LIGHT_GRAY)
            .setTextAlignment(TextAlignment.CENTER)
            .setPadding(5);
    }
}
